package com.yuan.algorithms.编程珠玑;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;

/**
 * @author YouYuan
 * @contact 1265161633@qq.com
 * @date 2016年2月29日 下午4:12:48
 * @descript
 */
public class 磁盘文件排序 {

	static String filePath = "E:/Test/Develop/DiskFileSort/file.txt";
	static String savePath = "E:/Test/Develop/DiskFileSort/sortFile.txt";

	public static void main(String[] args) {
		// 生成排序文件
		createSortFile(10000000);

		long start = System.currentTimeMillis();
		// 进行排序
		diskSort(savePath);
		long end = System.currentTimeMillis();
		System.out.println("Time:"+(end-start));
	}

	private static void diskSort(String path) {
		boolean[] hashArr = new boolean[10000000];
		File fileR = new File(filePath);
		File fileW = new File(savePath);
		
		FileReader fr = null;
		FileWriter fw = null;
		try {
			fileW.createNewFile();
			fw = new FileWriter(fileW);
		} catch (IOException e) {
			e.printStackTrace();
		}
		BufferedWriter bfwriter = new BufferedWriter(fw);
		try {
			fr = new FileReader(fileR);
		} catch (IOException e) {
			e.printStackTrace();
		}
		BufferedReader bfreader = new BufferedReader(fr);
		String temp = null;
		do {
			try {
				temp = bfreader.readLine();
				if (temp == null) {
					break;
				}
				int n = Integer.parseInt(temp);
				hashArr[n - 1000000] = true;
			} catch (IOException e) {
				e.printStackTrace();
			}
		} while (true);
		
		try {
			bfreader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		for (int i = 0, m = 0; i < hashArr.length; i++) {
			if (hashArr[i]) {
				try {
					if (m != 0) {
						bfwriter.newLine();
					} else {
						m = 1;
					}
					int n = i + 1000000;
					bfwriter.write("" + n);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		try {
			bfwriter.flush();
			bfwriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void createSortFile(int k) {
		Random random = new Random();
		File file = new File(filePath);
		FileWriter fw = null;
		try {
			file.createNewFile();
			fw = new FileWriter(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		BufferedWriter bfwriter = new BufferedWriter(fw);
		for (int i = 1; i < k; i++) {
			int n = 0;
			while (n < 1000000)
				n = (int) (random.nextFloat() * 10000000);
			try {
				if (i != 1) {
					bfwriter.newLine();
				}
				bfwriter.write("" + n);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			bfwriter.flush();
			bfwriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
